import { Component } from 'react'
import { View, Text, Input, Button, Picker } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { calculateRelationship, reverseLookup } from '../../utils/relativesCalculator'
import './index.scss'

interface FamilyMember {
  id: string
  name: string
  relationship: string
  relationshipToUser: string
}

interface TreeNode {
  id: string
  name: string
  relationship: string
  level: number
  children: TreeNode[]
}

interface State {
  familyMembers: FamilyMember[]
  newMemberName: string
  newMemberRelationship: string
  selectedRelationship: string
  region: string
  viewMode: 'list' | 'tree'
}

export default class FamilyTree extends Component<{}, State> {
  state: State = {
    familyMembers: [],
    newMemberName: '',
    newMemberRelationship: '',
    selectedRelationship: '',
    region: 'mandarin',
    viewMode: 'list'
  }

  relationships = [
    '父亲', '母亲', '儿子', '女儿', '丈夫', '妻子',
    '爷爷', '奶奶', '外公', '外婆', '孙子', '孙女',
    '哥哥', '姐姐', '弟弟', '妹妹', '叔叔', '阿姨',
    '舅舅', '姑姑', '伯父', '伯母', '堂哥', '堂弟',
    '表哥', '表姐', '女婿', '儿媳', '养父', '养母'
  ]

  componentDidMount() {
    // 从本地存储加载家谱数据
    this.loadFamilyData()
  }

  // 从本地存储加载家谱数据
  loadFamilyData = () => {
    try {
      const savedData = Taro.getStorageSync('familyTreeData')
      if (savedData) {
        const parsedData = JSON.parse(savedData)
        this.setState({
          familyMembers: parsedData.familyMembers || [],
          region: parsedData.region || 'mandarin'
        })
      }
    } catch (error) {
      console.error('加载家谱数据失败:', error)
    }
  }

  // 保存家谱数据到本地存储
  saveFamilyData = () => {
    try {
      const { familyMembers, region } = this.state
      const dataToSave = {
        familyMembers,
        region
      }
      Taro.setStorageSync('familyTreeData', JSON.stringify(dataToSave))
    } catch (error) {
      console.error('保存家谱数据失败:', error)
    }
  }

  handleAddMember = () => {
    const { newMemberName, selectedRelationship, region, familyMembers } = this.state
    
    if (!newMemberName.trim() || !selectedRelationship) {
      return
    }

    // 计算与用户的关系
    let relationshipToUser = selectedRelationship
    if (familyMembers.length > 0) {
      // 这里可以添加更复杂的逻辑来计算与其他成员的关系
      // 暂时使用直接关系
      relationshipToUser = selectedRelationship
    }

    const newMember: FamilyMember = {
      id: Date.now().toString(),
      name: newMemberName.trim(),
      relationship: selectedRelationship,
      relationshipToUser
    }

    this.setState({
      familyMembers: [...familyMembers, newMember],
      newMemberName: '',
      selectedRelationship: ''
    }, () => {
      this.saveFamilyData() // 保存数据到本地存储
    })
  }

  handleDeleteMember = (id: string) => {
    this.setState({
      familyMembers: this.state.familyMembers.filter(member => member.id !== id)
    }, () => {
      this.saveFamilyData() // 保存数据到本地存储
    })
  }

  handleRegionChange = (e: any) => {
    this.setState({ region: e.detail.value }, () => {
      this.saveFamilyData() // 保存数据到本地存储
    })
  }

handleRelationshipChange = (e: any) => {
    this.setState({
      selectedRelationship: this.relationships[e.detail.value]
    })
  }

  toggleViewMode = () => {
    this.setState({
      viewMode: this.state.viewMode === 'list' ? 'tree' : 'list'
    })
  }

  // 清空所有成员
  handleClearAll = () => {
    Taro.showModal({
      title: '确认清空',
      content: '确定要清空所有家庭成员吗？此操作不可撤销。',
      success: (res) => {
        if (res.confirm) {
          this.setState({
            familyMembers: []
          }, () => {
            this.saveFamilyData() // 保存数据到本地存储
            Taro.showToast({
              title: '已清空所有成员',
              icon: 'success'
            })
          })
        }
      }
    })
  }

  // 清除本地存储数据
  handleClearStorage = () => {
    Taro.showModal({
      title: '确认清除',
      content: '确定要清除所有本地存储的家谱数据吗？此操作不可撤销。',
      success: (res) => {
        if (res.confirm) {
          try {
            Taro.removeStorageSync('familyTreeData')
            this.setState({
              familyMembers: [],
              region: 'mandarin'
            })
            Taro.showToast({
              title: '数据已清除',
              icon: 'success'
            })
          } catch (error) {
            console.error('清除数据失败:', error)
            Taro.showToast({
              title: '清除失败',
              icon: 'none'
            })
          }
        }
      }
    })
  }

  // 构建家谱树结构
  buildFamilyTree = (): TreeNode[] => {
    const { familyMembers } = this.state
    
    // 首先找到根节点（通常是用户自己或父母辈）
    const rootMembers = familyMembers.filter(member => 
      ['父亲', '母亲', '爷爷', '奶奶', '外公', '外婆'].includes(member.relationship)
    )
    
    if (rootMembers.length === 0 && familyMembers.length > 0) {
      // 如果没有找到明确的根节点，使用第一个成员作为根
      const firstMember = familyMembers[0]
      return [{
        id: firstMember.id,
        name: firstMember.name,
        relationship: firstMember.relationship,
        level: 0,
        children: []
      }]
    }

    return rootMembers.map(member => ({
      id: member.id,
      name: member.name,
      relationship: member.relationship,
      level: 0,
      children: this.buildChildren(member, familyMembers, 1)
    }))
  }

  // 递归构建子节点
  buildChildren = (parent: FamilyMember, allMembers: FamilyMember[], level: number): TreeNode[] => {
    const children: TreeNode[] = []
    
    // 根据关系类型查找可能的子节点
    allMembers.forEach(member => {
      if (this.isChildRelationship(parent.relationship, member.relationship)) {
        children.push({
          id: member.id,
          name: member.name,
          relationship: member.relationship,
          level,
          children: this.buildChildren(member, allMembers, level + 1)
        })
      }
    })
    
    return children
  }

  // 判断是否为子关系
  isChildRelationship = (parentRel: string, childRel: string): boolean => {
    const parentChildMap: { [key: string]: string[] } = {
      '父亲': ['儿子', '女儿'],
      '母亲': ['儿子', '女儿'],
      '爷爷': ['父亲', '叔叔', '姑姑'],
      '奶奶': ['父亲', '叔叔', '姑姑'],
      '外公': ['母亲', '舅舅', '阿姨'],
      '外婆': ['母亲', '舅舅', '阿姨'],
      '儿子': ['孙子', '孙女'],
      '女儿': ['孙子', '孙女'],
      '丈夫': ['儿子', '女儿'],
      '妻子': ['儿子', '女儿']
    }
    
    return parentChildMap[parentRel]?.includes(childRel) || false
  }

  // 渲染树节点
  renderTreeNode = (node: TreeNode) => {
    const marginLeft = node.level * 20
    return (
      <View className='tree-node-container' style={{ marginLeft: `${marginLeft}px` }}>
        <View className='tree-node-content'>
          <Text className='node-name'>{node.name}</Text>
          <Text className='node-relation'>{node.relationship}</Text>
        </View>
        {node.children.length > 0 && (
          <View className='tree-node-children'>
            {node.children.map(child => (
              <View key={child.id} className='tree-node'>
                {this.renderTreeNode(child)}
              </View>
            ))}
          </View>
        )}
      </View>
    )
  }

  render() {
    const { familyMembers, newMemberName, selectedRelationship, region, viewMode } = this.state

    return (
      <View className='family-tree'>
        <View className='header'>
          <Text className='title'>家谱管理</Text>
          <Text className='subtitle'>管理您的家庭成员关系</Text>
        </View>

        <View className='control-section'>
          <Text className='control-title'>添加家庭成员</Text>
          
          <View className='input-group'>
            <Text className='input-label'>姓名</Text>
            <Input
              className='input-field'
              placeholder='输入家庭成员姓名'
              value={newMemberName}
              onInput={(e) => this.setState({ newMemberName: e.detail.value })}
            />
          </View>

          <View className='input-group'>
            <Text className='input-label'>与您的关系</Text>
            <Picker
              mode='selector'
              range={this.relationships}
              onChange={this.handleRelationshipChange}
              value={this.relationships.indexOf(selectedRelationship)}
            >
              <View className='select-field'>
                {selectedRelationship || '选择关系'}
              </View>
            </Picker>
          </View>

          <View className='input-group'>
            <Text className='input-label'>地区方言</Text>
            <Picker
              mode='selector'
              range={['普通话', '粤语', '上海话', '四川话']}
              onChange={this.handleRegionChange}
              value={['mandarin', 'cantonese', 'shanghainese', 'sichuanese'].indexOf(region)}
            >
              <View className='select-field'>
                {region === 'mandarin' ? '普通话' : 
                 region === 'cantonese' ? '粤语' :
                 region === 'shanghainese' ? '上海话' : '四川话'}
              </View>
            </Picker>
          </View>

          <View className='button-group'>
            <Button className='control-btn' onClick={this.handleAddMember}>
              添加成员
            </Button>
            <Button 
              className='control-btn secondary' 
              onClick={this.handleClearAll}
            >
              清空家谱
            </Button>
            <Button 
              className='control-btn danger' 
              onClick={this.handleClearStorage}
            >
              清除数据
            </Button>
          </View>
        </View>

        <View className='tree-section'>
          <View className='tree-header'>
            <Text className='tree-title'>
              {viewMode === 'list' ? '家庭成员列表' : '家谱树状图'}
            </Text>
            <Button 
              className='view-toggle-btn'
              onClick={this.toggleViewMode}
            >
              {viewMode === 'list' ? '切换到树状图' : '切换到列表'}
            </Button>
          </View>
          <View className='tree-container'>
            {familyMembers.length === 0 ? (
              <View className='empty-state'>
                <Text className='empty-icon'>👨‍👩‍👧‍👦</Text>
                <Text>暂无家庭成员，请添加第一个成员</Text>
              </View>
            ) : viewMode === 'list' ? (
              <View className='member-list'>
                {familyMembers.map(member => (
                  <View key={member.id} className='member-item'>
                    <Text className='member-name'>{member.name}</Text>
                    <Text className='member-relation'>
                      {member.relationship} ({member.relationshipToUser})
                    </Text>
                    <View className='member-actions'>
                      <Button 
                        className='action-btn edit'
                        onClick={() => {/* 编辑功能待实现 */}}
                      >
                        编辑
                      </Button>
                      <Button 
                        className='action-btn delete'
                        onClick={() => this.handleDeleteMember(member.id)}
                      >
                        删除
                      </Button>
                    </View>
                  </View>
                ))}
              </View>
            ) : (
              <View className='tree-view'>
                {this.buildFamilyTree().map(node => (
                  <View key={node.id} className='tree-node'>
                    {this.renderTreeNode(node)}
                  </View>
                ))}
              </View>
            )}
          </View>
        </View>
      </View>
    )
  }
}